package com.laike.pay.activity;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.laike.pay.R;
import com.laike.pay.base.BaseActivity;
import com.laike.pay.base.Constants;
import com.laike.pay.base.MyApplication;
import com.laike.pay.http.BaseCallback;
import com.laike.pay.http.HttpRetrofit;
import com.laike.pay.http.ParamsUtils;
import com.laike.pay.http.ProgressListener;
import com.laike.pay.http.Result;
import com.laike.pay.http.api.ApiName;
import com.laike.pay.http.api.SerivceApi;
import com.laike.pay.utils.SharedPreferencesUtils;
import com.laike.pay.utils.ToastUtils;
import com.laike.pay.utils.VersionUtil;
import com.orhanobut.logger.Logger;
import com.pax.gl.IGL;
import com.pax.ippi.dal.interfaces.IDal;
import com.pax.ippi.emv.interfaces.IEmv;
import com.pax.ippi.impl.NeptuneUser;

import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by wangshuo on 2017/5/13.
 * 首页
 */

public class HomepageActivity extends BaseActivity implements BaseCallback<Result<Map<String, Object>>> {
    @Bind(R.id.arrow)
    TextView arrow;
    @Bind(R.id.collect_money_layout)
    RelativeLayout collectMoneyLayout;
    @Bind(R.id.setting_layout)
    RelativeLayout settingLayout;
    @Bind(R.id.merchant_information_layout)
    RelativeLayout merchantInformationLayout;
    @Bind(R.id.space)
    TextView space;
    @Bind(R.id.unionPay_layout)
    RelativeLayout unionPayLayout;
    @Bind(R.id.back_main_menu)
    TextView mTextViewBackMenu;
    @Bind(R.id.menu_back_scroll)
    RelativeLayout mScrollView;
    final String TAG = "HomepageActivity";
    private ProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);

    }

    @Override
    public int getContentViewResId() {
        return R.layout.activity_homepage;
    }

    @Override
    public void intiViews() {
        HttpRetrofit.getInstance().getInterfaceApi(SerivceApi.class).login(SharedPreferencesUtils.getAppid(), ApiName.LOGIN,
                ParamsUtils.login(), SharedPreferencesUtils.getTerminalNumber(), SharedPreferencesUtils.getWorkMenId()
        ).enqueue(this);
//        getNewVersion();
        collectMoneyLayout.setOnClickListener(this);
        settingLayout.setOnClickListener(this);
        merchantInformationLayout.setOnClickListener(this);
        unionPayLayout.setOnClickListener(this);
        mTextViewBackMenu.setOnClickListener(this);
        mTextViewBackMenu.setVisibility(View.GONE);
        mScrollView.setOnTouchListener(shopCarSettleTouch);
    }

    private View.OnTouchListener shopCarSettleTouch = new View.OnTouchListener() {
        private float startX, offsetX;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int ea = event.getAction();
            switch (ea) {
                case MotionEvent.ACTION_DOWN:
                    startX = (int) event.getRawX();//获取触摸事件触摸位置的原始X坐标
                case MotionEvent.ACTION_MOVE:
                    offsetX = event.getX() - startX;
                    if (offsetX > 200) {
                        mTextViewBackMenu.setVisibility(View.VISIBLE);
                    }
                    if (offsetX < -150) {
                        mTextViewBackMenu.setVisibility(View.GONE);
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    break;
            }
            return true;
        }
    };

    /**
     * 获取新版本
     */
    private void getNewVersion() {
        HttpRetrofit.getInstance().getInterfaceApi(SerivceApi.class).updateVersion(ApiName.UPDATE_VERSION, Constants.NEW_VERSION_NAME,
                ParamsUtils.getUpdateVersion()).enqueue(new Callback<Result<Map<String, String>>>() {
            @Override
            public void onResponse(Call<Result<Map<String, String>>> call, Response<Result<Map<String, String>>> response) {
                if (response.body().getStatus().equals("1")) {
                    Map<String, String> result = response.body().getResult();
                    String mUpdateVersion = result.get("bf_laike_version");//最新版本号
                    String mApkUrl = result.get("bf_laike_download");//下载地址
                    String mCurrentVersion = VersionUtil.getVersionName(MyApplication.getApp());//当前版本
                    int versionType = VersionUtil.compareVersionName(mUpdateVersion, mCurrentVersion);
                    // 0相等  1前者大 2后者大
                    if (versionType == 1) {
                        File dir = new File(Constants.DOWNLOAD_DIR);
                        //删除已存在的apk
                        if (dir.exists()) {
                            File[] files = dir.listFiles();
                            for (File file : files) {
                                try {
                                    if (file.getName().contains("apk")) {
                                        VersionUtil.deleteFileSafely(file);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        showDownLoadAlertDialog(mApkUrl, mUpdateVersion);
                    }
                }
            }

            @Override
            public void onFailure(Call<Result<Map<String, String>>> call, Throwable t) {
                Log.v("onFailure", "error message:" + t.getMessage());
            }
        });
    }

    private void showDownLoadAlertDialog(final String apkUrl, final String version) {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setCancelable(false)
                .setTitle("提示")//设置对话框的标题
                .setMessage("发现新版本，是否下载？")//设置对话框的内容
                //设置对话框的按钮
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        getDownLoadData(apkUrl, version);
                    }
                }).create();
        dialog.show();
    }

    private void getDownLoadData(String apkUrl, final String mUpdateVersion) {

        HttpRetrofit.loadFile(apkUrl, new ProgressListener() {
            @Override
            public void onProgress(long progress, long total, boolean done) {
                final float perfloat = (float) progress / (float) total * (float) 100;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showDownLoadProgressDialog(perfloat);
                    }
                });
            }

            @Override
            public void onHttpSuccess(byte[] bytes) {
                super.onHttpSuccess(bytes);
                String savepath = Constants.DOWNLOAD_DIR + mUpdateVersion + ".apk";
                final File file = new File(savepath);
                try {
                    VersionUtil.byte2File(bytes, file.getParent(), file.getName());
                    dialog.dismiss();
                    VersionUtil.installApk(MyApplication.getApp(), file.getPath());
                } catch (Exception e) {
                    Logger.d(e);
                } finally {
                    dialog.dismiss();
                }
            }

            @Override
            public void onException(Throwable e) {
                super.onException(e);
                dialog.dismiss();
                Log.d(TAG, e.getMessage());
            }
        });
    }

    private void showDownLoadProgressDialog(float progress) {
        if (dialog == null) {
            dialog = new ProgressDialog(this);
            dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            dialog.setCanceledOnTouchOutside(false);
            dialog.setMessage("正在下载");
            dialog.setMax(100);
            dialog.setProgress((int) progress);
            dialog.show();
        } else {
            dialog.setProgress((int) progress);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        HttpRetrofit.getInstance().getInterfaceApi(SerivceApi.class).login(SharedPreferencesUtils.getAppid(), ApiName.LOGIN,
                ParamsUtils.login(), SharedPreferencesUtils.getTerminalNumber(), SharedPreferencesUtils.getWorkMenId()
        ).enqueue(this);
    }

    @Override
    public String setTitle() {
        return "";
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        int id = view.getId();
        switch (id) {
            case R.id.collect_money_layout://收银
                Intent intent1 = new Intent(this, CollectMoneyActivity.class);
                startActivity(intent1);
                break;
            case R.id.setting_layout://设置
                Intent intent2 = new Intent(this, SettingActivity.class);
                startActivity(intent2);
                break;
            case R.id.merchant_information_layout://商户信息
                Intent intent3 = new Intent(this, MerchantInfoActivity.class);
                startActivity(intent3);
                break;
            case R.id.unionPay_layout://银联
                sign();
                break;
            case R.id.back_main_menu://返回主菜单
//                Intent intent = new Intent(Intent.ACTION_MAIN);
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                intent.addCategory(Intent.CATEGORY_HOME);
//                startActivity(intent);
                AlertDialog dialog = new AlertDialog.Builder(this)
                        .setCancelable(false)
                        .setTitle("提示")//设置对话框的标题
                        .setMessage("确定退出收银系统吗？")//设置对话框的内容
                        //设置对话框的按钮
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                android.os.Process.killProcess(android.os.Process.myPid());
                            }
                        }).create();
                dialog.show();
                break;
        }
    }

    @Override
    public void onAttachedToWindow() {
        this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
        super.onAttachedToWindow();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_HOME) {
            Intent intent = new Intent(this, HomepageActivity.class);
            startActivity(intent);
            return true;
        }
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //不作处理
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 签到
     */
    private void sign() {
        new Thread(new Runnable() {
            public void run() {
                try {
                    JSONObject json = new JSONObject();
                    json.put("transType", "LOGON");
                    json.put("appId", SharedPreferencesUtils.getAppid());
                    json.put("operId", "01");//签到操作员号码01
                    String result = payHelper.doTrans(json.toString());
                    json = new JSONObject(result);
                    final String rspCode = json.getString("rspCode");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if ("0".equals(rspCode)) {
                                Toast.makeText(HomepageActivity.this, "签到成功", Toast.LENGTH_SHORT).show();
                            } else
                                Toast.makeText(HomepageActivity.this, "签到失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    public void onResponse(Call<Result<Map<String, Object>>> call, Response<Result<Map<String, Object>>> response) {
        if (response.code() == 200) {
            if (response.body().getStatus().equals("1")) {
                Log.v("onResponse", "message:" + response.body());
                Map<String, Object> result = response.body().getResult();
                Map<String, String> map = new HashMap<>();
                String shopName = ((Map<String, String>) result.get("mer")).get("real_name");
                String bankCardName = ((Map<String, String>) result.get("mer")).get("bank_account_name");
                String bankCard = ((Map<String, String>) result.get("mer")).get("bank_card");
                String url = ((Map<String, String>) result.get("terminal")).get("url");
                map.put(Constants.SHOP_NAME, shopName);
                map.put(Constants.BANK_ACOUNT_NAME, bankCardName);
                map.put(Constants.BANK_NUMBER, bankCard);
                map.put(Constants.URL, url);
                SharedPreferencesUtils.addMultipleToSharedPreferences(this, Constants.SHOP_INFO_SP_NAME, map);
            } else {
                Log.v("onFailure", "error message:" + response.body().getInfo());
            }
        }
    }

    @Override
    public void onFailure(Call<Result<Map<String, Object>>> call, Throwable t) {
        ToastUtils.showToast(this, getString(R.string.login_fail));
        Log.v("onFailure", "error message:" + t.getMessage());
    }
}
